<template>
  <div class="player-container">
    <div class="room-btn">
      <a-button @click="joinRoom">发起通话</a-button>
      <a-button @click="leaveRoom">结束通话</a-button>
    </div>
    <UserPlayer
      :roomStore="roomStore"
      :tracks="tracks"
      :subscribedTracks="subscribedTracks"
      :addShouldResumedTracks="addShouldResumedTracks"
    />
  </div>
</template>

<script setup lang="ts">
import QNRTC, { QNConnectionState, QNLocalTrack, QNTrack as RTCTrack, QNLogLevel } from 'qnweb-rtc'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { RoomStore } from './roomStore/index'
import UserPlayer from './components/UserPlayer.vue'
import { message } from 'ant-design-vue'

QNRTC.setLogLevel(QNLogLevel.NONE)

const props = defineProps({
  roomid: {
    type: String,
    default: 'zxh_',
  },
})
const emits = defineEmits(['publishRoom', 'deviceLeaveRoom'])
// 创建房间存储实例
const roomStore = ref(
  new RoomStore((type) => {
    console.log(type, 'type')
    if (type === 'leave') {
      emits('deviceLeaveRoom')
    }
  }),
)
const tracks = computed(() => Array.from(roomStore.value.publishedTracks.values()))
const subscribedTracks = computed(() => Array.from(roomStore.value.subscribedTracks.values()))
const addShouldResumedTracks = roomStore.value.addShouldResumedTracks
// 加入房间
const joinRoom = async () => {
  if (roomStore.value.state !== QNConnectionState.DISCONNECTED) {
    console.warn('Room is not in disconnected state, cannot join again')
    return
  }
  try {
    // 1. 先获取轨道（不依赖房间状态）
    const tracksResult = await selectTracks()

    // 2. 获取token
    roomStore.value.setroomId(props.roomid)
    const token = await roomStore.value.fetchRoomToken()

    // 3. 加入房间
    await roomStore.value.joinRoom(token)

    // 4. 发布轨道（确保在加入房间后）
    if (tracksResult) {
      await publish(tracksResult)
    }
    emits('publishRoom')
  } catch (error) {
    console.error('Failed to join room:', error)
    message.error('加入房间失败！')
    emits('deviceLeaveRoom')
  }
}
// 发布
const publish = (tracks: RTCTrack[]) => {
  roomStore.value
    .publish(tracks as QNLocalTrack[])
    .then(() => {
      console.log('Publish successful')
    })
    .catch((e) => {
      console.error('Publish failed:', e)
    })
}
// 选择播放源
const selectTracks = (): Promise<RTCTrack[] | undefined> => {
  return roomStore.value
    .getSelectTracks()
    .then((tracks) => {
      console.log('Selected tracks successfully, count:', tracks?.length || 0)
      return tracks
    })
    .catch((e) => {
      console.error('Failed to select tracks:', e)
      return undefined
    })
}
// 离开房间
const leaveRoom = () => {
  if (roomStore.value) {
    roomStore.value.leaveRoom()
  }
}
defineExpose({
  joinRoom,
  leaveRoom,
})

onUnmounted(() => {
  leaveRoom()
})
</script>

<style lang="less" scoped>
.player-container {
  width: 100%;
  height: 100%;
  .room-btn {
    position: absolute;
    display: flex;
    gap: 10px;
    top: 10px;
    right: 10px;
  }
}
</style>
